<template>
  <div class="app-container" style="width: 100%;">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item prop="deviceName">
        <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item prop="variableName">
        <el-input v-model="queryParams.variableName" placeholder="请输入监测指标" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-date-picker v-model="daterangeCreateDate" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="请选择开始日期" end-placeholder="请选择结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item prop="alarmLevel">
        <el-select v-model="queryParams.alarmLevel" placeholder="请选择报警等级" clearable>
          <el-option v-for="dict in dict.type.oil_alarm_level" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="报警信息" prop="message">
        <el-input
          v-model="queryParams.message"
          placeholder="请输入报警信息"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item prop="processUser">
        <el-input v-model="queryParams.processUser" placeholder="请输入处理人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['oil:record:add']"
          >新增</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['oil:record:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['oil:record:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['oil:record:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="用户名称" align="center" prop="deptName" />
      <el-table-column label="设备编号" align="center" prop="code" />
      <el-table-column label="监测指标" align="center" prop="variableName" />
      <el-table-column label="报警等级" align="center" prop="alarmLevel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.oil_alarm_level" :value="scope.row.alarmLevel" />
        </template>
      </el-table-column>
      <el-table-column label="末次报警值" align="center" prop="value" />
      <el-table-column label="初次报警时间" align="center" prop="firstOccurTime" width="100" />
      <el-table-column label="末次报警时间" align="center" prop="lastOccurTime" width="100" />
      <el-table-column label="报警次数" align="center" prop="occurCount" />
      <el-table-column label="报警原因" align="center" prop="message" />
      <el-table-column label="处理状态" align="center" prop="state">
        <template slot-scope="scope">
          <span :class="scope.row.state === 0 ? 'p1' : 'p2'">{{ scope.row.state == 0
            ? "未处理" : (scope.row.state == 1 ? "已处理" : "误报") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理人" align="center" prop="processBy" />
      <el-table-column label="处理时间" align="center" prop="processTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.processTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="维护建议" align="center" prop="remark" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['oil:record:edit']" v-if="scope.row.state == 0">处理</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['oil:record:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleCheck(scope.row)"
            v-hasPermi="['oil:record:list']">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改报警记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" readonly />
        </el-form-item>
        <el-form-item label="用户名称" prop="deptName">
          <el-input v-model="form.deptName" readonly />
        </el-form-item>
        <el-form-item label="设备编码" prop="code">
          <el-input v-model="form.code" readonly />
        </el-form-item>
        <el-form-item label="监测指标" prop="variableName">
          <el-input v-model="form.variableName" readonly />
        </el-form-item>
        <el-form-item label="报警日期" prop="createTime">
          <el-input v-model="form.createTime" readonly />
        </el-form-item>
        <el-form-item label="报警原因" prop="message">
          <el-input v-model="form.message" placeholder="报警原因" readonly />
        </el-form-item>
        <el-form-item label="处理状态" prop="state">
          <template>
            <el-radio v-model="form.state" :label="0">未处理</el-radio>
            <el-radio v-model="form.state" :label="1">处理完毕</el-radio>
            <el-radio v-model="form.state" :label="2">误报</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="处理备注" prop="processRemark">
          <el-input v-model="form.processRemark" placeholder="请输入备注" multiline />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-drawer :title="title" :visible.sync="open1" size="40%" append-to-body style="padding: 0">
      <div style="color: aliceblue; font-size: 14px;font-weight: bold;">
        <div class="row">
          <span class="column">工厂名称：{{ alarmDetail.deptName }}</span>
          <span class="column">首次报警：{{ alarmDetail.firstOccurTime }}</span>
          <span class="column">报警指标：{{ alarmDetail.variableName }}</span>
        </div>
        <div class="row">
          <span class="column">设备名称：{{ alarmDetail.deviceName }}</span>
          <span class="column">末次报警：{{ alarmDetail.lastOccurTime }}</span>
          <span class="column">报警原因：{{ alarmDetail.message }}</span>
        </div>
        <div class="row">
          <span class="column">设备编码：{{ alarmDetail.code }}</span>
          <span class="column">持续时间：{{ getTimeInterval(alarmDetail.firstOccurTime, alarmDetail.lastOccurTime) }}</span>
          <span class="column">报警次数：{{ alarmDetail.occurCount }}</span>
        </div>
        <!-- <div class="row">
          <span class="column">报警类型：<dict-tag style="display: inline;" :options="dict.type.oil_alarm_type" :value="alarmRuleDetail.alarmType" /></span>
          <span class="column">报警阈值：X:{{ alarmRuleDetail.maxValue }} &emsp; Y:{{ alarmRuleDetail.minValue }}</span>
          <span class="column">末次报警值：{{ alarmDetail.value }}</span>
        </div> -->
      </div>
      <div style="color: aliceblue; font-size: larger">
        <div style="margin-top: 20px;">维护建议</div>
        <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="alarmDetail.remark" style="margin-top: 10px;"
          readnoly>
        </el-input>
      </div>
      <div>
        <div style="margin-top: 20px;"><span style="color: aliceblue; font-size: larger;">健康分析</span></div>
        <el-radio-group size="mini" v-model="range" @input="timeChange" style="float: right;position: relative;z-index:999;">
          <el-radio-button label="0">实时</el-radio-button>
          <el-radio-button label="1">24H</el-radio-button>
          <el-radio-button label="2">72H</el-radio-button>
          <el-radio-button label="3" @click.native="showDatePicker = true">自定义</el-radio-button>
        </el-radio-group>
        <div id="chart-line" style="width: 100%; height: 400px;"></div>
      </div>
    </el-drawer>
    <el-dialog title="自定义时间" :visible.sync="showDatePicker" width="40%">
      <span style="color: #ffffff;">请选择时间段：</span>
      <el-date-picker v-model="timeRange" type="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期"
        :picker-options="pickerOptions" align="center" :default-time="['08:00:00']"></el-date-picker>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showDatePicker = false">取 消</el-button>
        <el-button type="primary" @click="confirmDate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRecord,
  getRecord,
  delRecord,
  addRecord,
  updateRecord,
} from "@/api/oil/record";
import * as echarts from "echarts";
import DateTool from "../../../utils/DateTool";
import { listVariableData } from '../../../api/oil/device_data';
import { getRule } from "@/api/oil/rule";
export default {
  name: "Record",
  dicts: ["oil_alarm_level","oil_alarm_type"],
  data() {
    return {

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报警记录表格数据
      recordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      // 备注时间范围
      daterangeCreateDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceName: null,
        sensorName: null,
        variableName: null,
        createDate: null,
        alarmLevel: null,
        message: null,
        state: null,
        processUser: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      alarmDetail: {},
      alarmRuleDetail:{},
      range: 0,
      endTime: null,
      startTime: null,
      variableData: [],
      xData: [],
      yData: [],
      legend: [],
      dataChart: null,
      showDatePicker: false,
      timeRange: null,
      pickerOptions: null
    };
  },

  created() {
    this.getList();
  },
  mounted() {
  },
  methods: {
    getAlarmRule(ruleId){
      getRule(ruleId).then(res=>{
        this.alarmRuleDetail = res.data;
      })
    },
    confirmDate() {
      console.log(this.timeRange);
      this.startTime = DateTool.dateToStr(this.timeRange[0]);
      this.endTime = DateTool.dateToStr(this.timeRange[1]);
      this.showDatePicker = false;
      this.getVariableData(this.alarmDetail);
    },
    //控制自定义查询时间时最长查询三个月
    initPickerOption() {
      this.pickerOptions = {
        // onPick：选中日期时的回调函数，在这里对选中的日期进行处理{maxDate：后选中日期；minDate：第一个选中的日期}
        onPick: ({ maxDate, minDate }) => {
          this.startDate = minDate && minDate.getTime()
          if (maxDate) {
            // 选中后一个时，要把第一个的赋值清空
            this.startDate = ''
          }
        },
        disabledDate: (time) => {
          // 选中第一个后，后一个前后3个月可选，超出的不可选，超出当前天也不可选，这里的月份按需求设定
          const minTime = new Date(this.startDate).setMonth(new Date(this.startDate).getMonth() - 3)
          const maxTime = new Date(this.startDate).setMonth(new Date(this.startDate).getMonth() + 3)
          return time.getTime() > Date.now() || (this.startDate ? (time.getTime() < minTime || time.getTime() > maxTime) : false)
        }
      }
    },
    timeChange() {
      var value = this.range;
      if (value == 0) {
        this.endTime = DateTool.now();
        this.startTime = DateTool.dateToStr(DateTool.addHour(null, -1));
      } else if (value == 1) {
        this.endTime = DateTool.now();
        this.startTime = DateTool.dateToStr(DateTool.addHour(null, -24));
      } else if (value == 2) {
        this.endTime = DateTool.now();
        this.startTime = DateTool.dateToStr(DateTool.addHour(null, -72));
      }
      if (value == 3) {
        this.showDatePicker = true;
      } else {
        this.getVariableData(this.alarmDetail);
      }
    },
    getVariableData(row) {
      var fields = [];
      fields.push(row.variableKey);
      var queryData = { "deviceCode": row.code, "fields": fields, startTime: this.startTime, endTime: this.endTime };
      listVariableData(queryData).then(res => {
        this.variableData = res.data;
        this.xData = this.variableData.map(item => item.timeStamp);
        this.legend = [];
        this.legend.push(row.variableName);
        this.yData = [];
        var obj = { name: row.variableName, type: 'line' };
        obj.data = this.variableData.map(item => item[row.variableKey]);
        this.yData.push(obj);
        this.renderChart();
      })
    },
    getTimeInterval(time1, time2) {
      var interval = DateTool.getTimeHourInterval(time1, time2).toFixed(2);
      if (interval < 1) {
        interval = DateTool.getTimeMinuteInterval(time1, time2).toFixed;
        return interval + "分钟";
      } else {
        return interval + "小时";
      }
    },
    renderChart() {
      this.dataChart.clear();
      var option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: this.legend,
          left: 10,
          top: 10,
          textStyle: {
            color: "#fff"
          }
        },
        dataZoom: [{ // 开启鼠标缩放
          type: 'inside', // 内置型数据区域缩放组件
          start: 0, // 数据窗口范围的起始百分比
          end: 100 // 数据窗口范围的结束百分比
        }, {
          xAxisIndex: [0]
        }],
        grid: {
          left: '1%',
          right: '1%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          // feature: {
          //     saveAsImage: {}
          // }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          axisLabel: {
            formatter: function (value) {
              var time = value.split(" ");
              var date = time[0].substring(5);
              return time[1] + "\n" + date
            },
            show: true,
            textStyle: {
              color: "#fff"
            }
          },
          data: this.xData
        },
        yAxis: {
          type: 'value',
          splitLine: { // 设置y轴分割线
            show: true
          },
          axisLabel: {
            textStyle: {
              color: "#fff"
            }
          }
        },
        series: this.yData
      }

      option && this.dataChart.setOption(option);
    },
    /** 查询报警记录列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateDate && "" != this.daterangeCreateDate) {
        this.queryParams.params["beginTime"] =
          this.daterangeCreateDate[0];
        this.queryParams.params["endTime"] = this.daterangeCreateDate[1];
      }
      listRecord(this.queryParams).then((response) => {

        this.recordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        ruleId: null,
        deviceId: null,
        deviceName: null,
        sensorId: null,
        sensorName: null,
        variableKey: null,
        variableName: null,
        createTime: null,
        alarmLevel: null,
        value: null,
        message: null,
        state: null,
        processUser: null,
        processTime: null,
        remark: null,
        createBy: null,
        code: null,
        deviceType: null
        // alarmReason:null,


      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加报警记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getRecord(id).then((response) => {

        this.form = response.data;
        console.log(this.form)
        this.open = true;
        this.title = "处理报警记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateRecord(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRecord(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除报警记录编号为"' + ids + '"的数据项？')
        .then(function () {
          return delRecord(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 查看按钮 */
    handleCheck(row) {
      this.title = "设备信息";
      this.open1 = true;
      this.alarmDetail = row;
      this.range = 0;
      this.getAlarmRule(row.ruleId);
      this.$nextTick(() => {
        // 调用图表渲染函数
        if(!this.dataChart) this.dataChart = echarts.init(document.getElementById("chart-line"));
        this.timeChange();
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "oil/record/export",
        {
          ...this.queryParams,
        },
        `record_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style>
.p1 {
  color: red
}

.p2 {
  color: green
}

.row {
  display: flex;
  justify-content: space-between;
  height: 50px;
  width: 100%;
}

.row .column {
  width: 25%;
  word-break: break-all;
}
</style>